"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/10/27
 */
import * as React from 'react'
import {commonStyles} from "../../assets/styles/common";

const FontAwesome = require('react-native-vector-icons/FontAwesome').default;
import AuthHeader from "../../component/AuthHeader";
import MyText from "../../component/MyText";
import Colors from "../../assets/styles/Colors";

const {Actions} = require("react-native-router-flux");
import Validator from "../../utils/Validator";
import {clearInterval} from "react-native";
import MyIcon from "../../component/icon";
import {AuthComponent} from "../../interface/index";

const {toastValidateError} = require('../../utils/tools');

const {View, ScrollView, TouchableOpacity} = require('react-native');
const {connect} = require('react-redux');
const {createForm} = require('rc-form');
const {List, InputItem, Button, Flex} = require('antd-mobile');
const {KeyboardAwareScrollView} = require('react-native-keyboard-aware-scroll-view');

class SignUpPage extends React.Component<AuthComponent, any> {

    timer: any;

    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            errors: {
                phone: false,
                password: false,
                verifycode: false,

            }
        }
    }


    componentWillUnmount(): void {
        clearInterval(this.timer);
        this.timer = null;
        this.props.dispatch({
            type: 'auth/clearTimer'
        })

    }

//发送验证码
    onSendSms = () => {
        const {form, dispatch} = this.props;
        let {phone} = form.getFieldsValue();
        if (phone && Validator.validator(phone.replace(/ /g, ''), Validator.phoneReg)) {
            dispatch({
                type: 'auth/sendSms',
                payload: {phone: phone.replace(/ /g, '')}
            });
            this.starTimer();
        } else {
            toastValidateError(null, '手机号不合法');
        }
    };


    checkCanRegister = () => {

    };

    /**
     * 注册
     */
    onSubmit = () => {
        const {dispatch, form} = this.props;


        // {validator: this.validator.bind(this)}
        form.validateFields((error, value) => {
            if (!error) {
                let {phone, password, verifycode} = form.getFieldsValue();
                const store_phone = phone.replace(/ /g, '');
                dispatch({
                    type: 'auth/signUp',
                    payload: {store_phone, password, verifycode}
                });
            } else {
                toastValidateError(error);
            }
        });
    };

    /**
     * 开启定时器
     */
    starTimer() {
        let {auth: {sending, coldDownTime,}, dispatch} = this.props;
        clearInterval(this.timer);
        console.log(sending);
        if (sending) return;

        this.timer = setInterval(() => {
            if (coldDownTime > 0) {
                dispatch({
                    type: 'auth/save',
                    payload: {sendButtonText: `${coldDownTime--}s 后重试`, sending: true}
                })
            } else {
                clearInterval(this.timer);
                this.timer = null;
                dispatch({
                    type: 'auth/clearTimer',
                })
            }
        }, 900)

    }


    //验证器
    validator = ({field}, value, callBack) => {
        const errors = this.state.errors;
        errors[field] = true;
        if (field === 'phone') {
            if (value) {
                errors[field] = !Validator.validator(value.replace(/ /g, ''), Validator.phoneReg);
            }
            if (errors[field]) {
                callBack('手机号不合法');
            } else {
                callBack();
            }
            this.setState({errors})
        } else if (field === 'password') {
            errors[field] = !(value && value.length >= 6);
            if (errors[field]) {
                callBack('密码不合法');
            } else {
                callBack();
            }
            this.setState({errors})
        } else if (field === 'verifycode') {
            errors[field] = !Validator.validator(value, Validator.numberReg);
            if (errors[field]) {
                callBack('验证码不合法');
            } else {
                callBack();
            }
            this.setState({errors})
        }
    };

    render() {
        const {getFieldProps} = this.props.form;

        const SenSmsBtn = ({title, loading = false, onPress}) => (
            <Button type="primary"
                    onClick={onPress}
                    title={title}
                    loading={this.props.auth.sending}
                    disabled={this.props.auth.sending}
                    style={[commonStyles.centerVH, {height: 26, width: 100}]}>
                <MyText style={{fontSize: 12, color: 'white'}}>{title}</MyText>
            </Button>);
        return (
            <View style={commonStyles.container}>
                <KeyboardAwareScrollView>
                    <List renderHeader={<AuthHeader text={'轻生活商家端'}/>}>
                        <InputItem  {...getFieldProps('phone', {
                            rules: [
                                {required: true, message: '手机号未填写'},
                                {validator: this.validator.bind(this)}
                            ]
                        })}
                                    placeholder="输入手机号"
                                    labelNumber={2}
                                    type="phone"
                                    clear
                                    error={this.state.errors.phone}
                                    extra={<SenSmsBtn title={this.props.auth.sendButtonText} onPress={this.onSendSms}/>}
                        >
                            <FontAwesome name="mobile" size={26} color={Colors.Primary}/>
                        </InputItem>

                        <InputItem  {...getFieldProps('verifycode', {
                            rules: [
                                {required: true, message: '验证码未填写'},
                                {validator: this.validator.bind(this)}
                            ]
                        })}
                                    placeholder="输入验证码"
                                    labelNumber={2}
                                    type="number"
                                    error={this.state.errors.verifycode}
                                    clear
                        >
                            <MyIcon name='icon-yanzheng' size={20} color={Colors.Primary}/>
                        </InputItem>

                        <InputItem  {...getFieldProps('password', {
                                rules: [
                                    {required: true, message: '密码未填写'},
                                    {validator: this.validator.bind(this)}
                                ]
                            }
                        )}
                                    placeholder="输入密码"
                                    labelNumber={2}
                                    type="password"
                                    error={this.state.errors.password}
                                    clear
                        >
                            <FontAwesome name="lock" size={26} color={Colors.Primary}/>
                        </InputItem>

                    </List>
                    <View style={{paddingVertical: 10, paddingHorizontal: 20}}>
                        <Button type="primary"
                                title="注册"
                                onClick={this.onSubmit.bind(this)}
                                style={{height: 40, marginBottom: 20}}>注册</Button>

                        <Flex justify="between" direction="column">
                            <TouchableOpacity onPress={Actions.signUp}>
                                <MyText color={'#666'}>点击注册表示同意《用户服务协议》</MyText>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={Actions.pop} style={{marginTop: 20}}>
                                <MyText color={'#666'}>已有账号立即登陆</MyText>
                            </TouchableOpacity>
                        </Flex>
                    </View>
                </KeyboardAwareScrollView>
            </View>
        );
    }
}

const Wrapper = createForm()(SignUpPage);
export default connect(
    ({auth}) => ({auth})
)(Wrapper);